package com.briup.prs;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.conf.Configured;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.KeyValueLineRecordReader;
import org.apache.hadoop.mapreduce.lib.input.KeyValueTextInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import org.apache.hadoop.mapreduce.lib.output.TextOutputFormat;
import org.apache.hadoop.util.Tool;
import org.apache.hadoop.util.ToolRunner;

import java.io.IOException;
import java.math.BigDecimal;

/**
 * @author adam
 * @date 2022/2/9
 */
public class Step7 extends Configured implements Tool {
    public static class S7Mapper extends Mapper<Text, Text, Text, Text> {
        @Override
//        key=用户:商品  value:推荐值
        protected void map(Text key, Text value, Context context) throws IOException, InterruptedException {
        context.write(key,value);
        }
    }
    public static class S7Reducer extends Reducer<Text,Text,Text,Text>{
        @Override
        protected void reduce(Text key, Iterable<Text> values, Context context) throws IOException, InterruptedException {
            BigDecimal sum=new BigDecimal(0);
            for (Text value : values) {
//                 累加
              sum=sum.add(new BigDecimal(value.toString()));
            }
            context.write(key,new Text(sum.toString()));
        }
    }
    @Override
    public int run(String[] strings) throws Exception {
        Configuration conf = getConf();
        String in = conf.get("in");

        String out = conf.get("out");
        Job job = Job.getInstance(conf, "step7");
        job.setJarByClass(Step7.class);
        conf.set(KeyValueLineRecordReader.KEY_VALUE_SEPARATOR,"\t");
        job.setInputFormatClass(KeyValueTextInputFormat.class);
        KeyValueTextInputFormat.addInputPath(job,new Path(in));
        job.setMapOutputValueClass(Text.class);
        job.setMapOutputKeyClass(Text.class);
        job.setMapperClass(S7Mapper.class);

        job.setReducerClass(S7Reducer.class);
        job.setOutputFormatClass(TextOutputFormat.class);
        TextOutputFormat.setOutputPath(job,new Path(out));
        job.setOutputKeyClass(Text.class);
        job.setOutputValueClass(Text.class);
        job.waitForCompletion(true) ;
        return 0;
    }

    public static void main(String[] args) throws Exception {
        ToolRunner.run(new Step7(),args);
    }
}
